import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:get/get.dart';
import 'package:grab_the_order/app/data/services/permission_service.dart';
import 'package:grab_the_order/app/routes/app_pages.dart';

class HomeController extends GetxController {
  final service = FlutterBackgroundService();
  final permissionService = Get.find<PermissionService>();

  var isServiceRunning = false.obs;
  var ordersGrabbedToday = 0.obs;
  var runningDuration = "00:00:00".obs;

  StreamSubscription<Map<String, dynamic>?>? _statusSubscription;

  @override
  void onInit() {
    super.onInit();
    
    // 建立服务状态监听，这是后台与UI联动的关键
    _statusSubscription = service.on('running').listen((event) {
      isServiceRunning.value = true;
      if (event != null && event.containsKey('duration')) {
        runningDuration.value = event['duration'];
      }
    });

    service.on('stopped').listen((event) {
      isServiceRunning.value = false;
      runningDuration.value = "00:00:00";
    });

    // 页面初始化时，主动查询一次当前状态，以同步UI
    // 这确保了如果服务已经在后台运行，用户再次进入APP时UI是正确的
    service.isRunning().then((value) {
      isServiceRunning.value = value;
      if (!value) {
         runningDuration.value = "00:00:00";
      }
    });

    service.on('update_ui').listen((event) {
       if (event != null && event.containsKey('orders_grabbed')) {
        ordersGrabbedToday.value += event['orders_grabbed'] as int;
      }
    });
  }

  // 【核心逻辑】用户手动点击按钮，触发服务状态切换
  Future<void> toggleService() async {
    final isRunning = await service.isRunning();

    if (isRunning) {
      // 如果服务正在运行，则停止它
      service.invoke('stop_service');
      // 乐观更新UI
      isServiceRunning.value = false;
      runningDuration.value = "00:00:00";
    } else {
      // 如果服务已停止，则启动它
      
      // 启动前给一个明确的提示
      Get.snackbar(
        "服务正在启动...", 
        "请确保所有权限已开启，可前往“我的”-“权限自检”确认。",
        backgroundColor: Colors.lightBlue,
        colorText: Colors.white,
        duration: const Duration(seconds: 4),
        mainButton: TextButton(
          onPressed: () => Get.toNamed(Routes.PERMISSION_CHECK),
          child: const Text("检查权限", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
        )
      );
      
      // 启动服务
      await service.startService();
      // 乐观更新UI
      isServiceRunning.value = true;
    }
  }

  @override
  void onClose() {
    _statusSubscription?.cancel();
    super.onClose();
  }
}